package com.mypack.dao.helper;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;

/**
 * generic dao support
 * this class implemented common used methods
 * @param <T> target entity class
 */
public class DaoSupport<T> {
	private Class<T> clazz;
	
	public DaoSupport() {
		clazz = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass())
					.getActualTypeArguments()[0];
	}
	
	public DaoSupport(Class<T> entityClazz) {
		clazz = entityClazz;
	}
	
	/**
	 * get jpa entity manager from current context
	 * @return em
	 */
	protected EntityManager getEM() {
		return JpaHelper.getEntityManager();
	}
	
	/**
	 * find all entitys, first 100 records
	 */
	public List<T> findAll() {
		return getEM().createQuery("select from " + clazz.getName()).setMaxResults(100).getResultList();
	}
	
	/**
	 * query for total count
	 */
	public Long findCount() {
		return (Long) getEM().createQuery("select count(o) from " + clazz.getName() + " o").getSingleResult();
	}
	
	/**
	 * find entity by page
	 * @param fistResult start index
	 * @param maxResult max index
	 */
	public List<T> findByPage(int fistResult, int maxResult) {
		return getEM().createQuery("from " + clazz.getName())
			.setFirstResult(fistResult).setMaxResults(maxResult).getResultList();
	}
	
	/**
	 * insert a new entity
	 */
	public void persist(T entity) {
		getEM().persist(entity);
	}
	
	/**
	 * remove an entity
	 */
	public void remove(T entity) {
		getEM().remove(entity);
	}
	
	/**
	 * remove all entity
	 */
	public void removeAll() {
		getEM().createQuery("delete " + clazz.getName());
	}
	
	/**
	 * update an entity
	 */
	public void merge(T entity) {
		getEM().merge(entity);
	}
	
}
